package com.flca.frw.util
{
	import mx.rpc.soap.WebService;
	import mx.rpc.soap.SOAPHeader;
	import mx.rpc.http.HTTPService;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.events.Event;
	import mx.rpc.events.ResultEvent;
	
	public class RemotingUtil 
	{
		private var callback:Function;
		private var loader:URLLoader = new URLLoader();
		
		public function loadXml(aXmlFileName:String, aResultCallBack:Function, aFaultCallBack:Function):void
		{
			if (Parameters.useMock) {
				loadXmlViaMock(aXmlFileName, aResultCallBack, aFaultCallBack);
			} else {
				loadXmlViaHttp(aXmlFileName, aResultCallBack, aFaultCallBack);
			}
		}
		
		private function loadXmlViaHttp(aXmlFileName:String, aResultCallBack:Function, aFaultCallBack:Function):void
		{
			var xmlLoader:HTTPService;
			
			xmlLoader = new HTTPService();
			xmlLoader.resultFormat = "e4x";
			xmlLoader.url = aXmlFileName;
			xmlLoader.addEventListener("fault", aFaultCallBack);
			xmlLoader.addEventListener("result", aResultCallBack);
			xmlLoader.send();
		}

		private function loadXmlViaMock(aXmlFileName:String, aResultCallBack:Function, aFaultCallBack:Function):void
		{
			callback = aResultCallBack;
			var request:URLRequest = new URLRequest(aXmlFileName);
			loader.load(request);
			loader.addEventListener(Event.COMPLETE, mockComplete);
		}
		
		private function mockComplete(aEvent:Event) : void {
			var re:ResultEvent = new ResultEvent("complete", false, true, XML(loader.data));
			callback(re);
		}

		public static function setHeader(aWs:WebService, aToken:String):void
		{
			var headers:Array;
			var header:SOAPHeader;
			var qname:QName;
			var ns:Namespace;
			
			ns = new Namespace("SecurityToken");
			qname = new QName(ns);
			header = new SOAPHeader(qname, aToken);
			
			headers = aWs.headers;
			headers.splice(0, headers.length);
			headers.push(header);
		}
	}
}